package com.quantstack.llcommonlibrary.view;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/2/22 10:06
 * @Notes
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class CountDownButton extends AppCompatButton {


    public CountDownButton(@NonNull Context context) {
        this(context,null);
    }

    public CountDownButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context,attrs,0);
    }

    public CountDownButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 开始倒计时
     * @param time
     */
    private Disposable timeDisposable;
    public void startTime(final int time){
        if(time<1){
            Log.e("CountDownButton","时间应该大于0");
            return;
        }
        timeDisposable = Observable.interval(0,1, TimeUnit.SECONDS).take(time)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        setText((time-aLong)+"S");
                        if(onTimeListener!=null){
                            if(aLong==0){
                                onTimeListener.onStartTimeDown();
                            }else if((aLong+1)==time){
                                onTimeListener.onEndTimeDown();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(timeDisposable!=null){
            timeDisposable.dispose();
        }
    }

    private OnTimeListener onTimeListener;
    public interface OnTimeListener{
        void onStartTimeDown();
        void onEndTimeDown();
    }

    public void setOnTimeListener(OnTimeListener onTimeListener){
        this.onTimeListener = onTimeListener;
    }
}

